package io.renren.modules.yckj.controller;

import io.renren.common.annotation.LogOperation;
import io.renren.common.constant.Constant;
import io.renren.common.page.PageData;
import io.renren.common.utils.ExcelUtils;
import io.renren.common.utils.Result;
import io.renren.common.validator.AssertUtils;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddGroup;
import io.renren.common.validator.group.DefaultGroup;
import io.renren.common.validator.group.UpdateGroup;
import io.renren.modules.yckj.dto.MachineDTO;
import io.renren.modules.yckj.dto.ProjectDTO;
import io.renren.modules.yckj.dto.ProjectMachineDTO;
import io.renren.modules.yckj.excel.ProjectMachineExcel;
import io.renren.modules.yckj.service.MachineService;
import io.renren.modules.yckj.service.ProjectMachineService;
import io.renren.modules.yckj.service.ProjectService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 项目机器关系表
 *
 * @author Mark sunlightcs@gmail.com
 * @since 1.0.0 2025-04-24
 */
@RestController
@RequestMapping("yckj/projectmachine")
@Tag(name = "项目机器关系表")
public class ProjectMachineController {
    @Autowired
    private ProjectMachineService projectMachineService;

    @Autowired
    private ProjectService projectService;

    @Autowired
    private MachineService machineService;

    @GetMapping("page")
    @Operation(summary = "分页")
    @Parameters({
            @Parameter(name = Constant.PAGE, description = "当前页码，从1开始", in = ParameterIn.QUERY, required = true, ref = "int"),
            @Parameter(name = Constant.LIMIT, description = "每页显示记录数", in = ParameterIn.QUERY, required = true, ref = "int"),
            @Parameter(name = Constant.ORDER_FIELD, description = "排序字段", in = ParameterIn.QUERY, ref = "String"),
            @Parameter(name = Constant.ORDER, description = "排序方式，可选值(asc、desc)", in = ParameterIn.QUERY, ref = "String")

    })
    @RequiresPermissions("yckj:project:page")
    public Result<PageData<ProjectMachineDTO>> page(@RequestParam Map<String, Object> params) {
        PageData<ProjectMachineDTO> page = projectMachineService.page(params);

        return new Result<PageData<ProjectMachineDTO>>().ok(page);
    }

    @GetMapping("list")
    @Operation(summary = "列表")
    @Parameters({
            @Parameter(name = "projectId", description = "项目Id", in = ParameterIn.QUERY, required = true, ref = "long"),
            @Parameter(name = "machineId", description = "机器Id", in = ParameterIn.QUERY, required = true, ref = "long")
    })
//    @RequiresPermissions("yckj:project:page")
    public Result<List<ProjectMachineDTO>> list(@RequestParam Map<String, Object> params) {
        List<ProjectMachineDTO> list = projectMachineService.getProjectMachineList(params);
        return new Result<List<ProjectMachineDTO>>().ok(list);
    }

    @GetMapping("{id}")
    @Operation(summary = "信息")
    @RequiresPermissions("yckj:project:info")
    public Result<ProjectMachineDTO> get(@PathVariable("id") Long id) {
        ProjectMachineDTO data = projectMachineService.get(id);
        return new Result<ProjectMachineDTO>().ok(data);
    }

    @PostMapping
    @Operation(summary = "保存")
    @LogOperation("保存")
    @RequiresPermissions("yckj:project:save")
    public Result save(@RequestBody ProjectMachineDTO dto) {
        Map<String, Object> params = new HashMap<>();
        params.put("machineId", dto.getMachineId());
        params.put("projectId", dto.getProjectId());
        List<ProjectMachineDTO> list = projectMachineService.list(params);
        if (!list.isEmpty()) {
            return new Result().error(1, "已存在，请勿重复添加");
        } else {
            ProjectDTO projectDTO = projectService.get(dto.getProjectId());
            if (projectDTO != null)
                dto.setProjectName(projectDTO.getName());
            MachineDTO machineDTO = machineService.get(dto.getMachineId());
            if (machineDTO != null)
                dto.setMachineName(machineDTO.getName());
            //效验数据
            ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
            dto.setCreateTime(new Date());
            dto.setUpdateTime(new Date());
            projectMachineService.save(dto);
        }
        return new Result();
    }

    @PutMapping
    @Operation(summary = "修改")
    @LogOperation("修改")
    @RequiresPermissions("yckj:project:update")
    public Result update(@RequestBody ProjectMachineDTO dto) {
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);
        dto.setUpdateTime(new Date());
        ProjectDTO projectDTO = projectService.get(dto.getProjectId());
        if (projectDTO != null)
            dto.setProjectName(projectDTO.getName());
        MachineDTO machineDTO = machineService.get(dto.getMachineId());
        if (machineDTO != null)
            dto.setMachineName(machineDTO.getName());
        projectMachineService.update(dto);

        return new Result();
    }

    @DeleteMapping
    @Operation(summary = "删除")
    @LogOperation("删除")
    @RequiresPermissions("yckj:project:delete")
    public Result delete(@RequestBody Long[] ids) {
        //效验数据
        AssertUtils.isArrayEmpty(ids, "id");

        projectMachineService.delete(ids);

        return new Result();
    }

    @GetMapping("export")
    @Operation(summary = "导出")
    @LogOperation("导出")
    @RequiresPermissions("yckj:project:export")
    public void export(@RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
        List<ProjectMachineDTO> list = projectMachineService.list(params);

        ExcelUtils.exportExcelToTarget(response, null, "项目机器关系表", list, ProjectMachineExcel.class);
    }

}